package pl.project.engineering.services;

import com.google.common.collect.Lists;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 *
 * @author ikrzysiek
 */
@Slf4j
@Data
public class LogFileList {

  private List<String> logFiles;
  private Path logDir;
  
  @Inject
  private AppConfig appConfig;
  
  public LogFileList(){
    logFiles = Lists.newArrayList();
  }
  
  public List<String> getLogFiles(){
    populateList();
    return logFiles;
  }

  private void populateList() {
    logFiles.clear();
    logDir = Paths.get(appConfig.getApplicationJarDir(),"logs").normalize();
    System.out.println(logDir);
    
    if (logDir.toFile().isDirectory()) {
      for (File file : logDir.toFile().listFiles()) {
        logFiles.add(file.getName());
      }
    }
    Collections.sort(logFiles);
  }

  public InputStream getFileAsStream(String fileName){
    File file = logDir.resolve(fileName).normalize().toFile();
    InputStream inputStream = null;
    try {
      if (file.exists()) {
        inputStream = new FileInputStream(file);
      }
    } catch (FileNotFoundException e) {
      log.warn("File " + fileName + " not found", e);
    } finally {
      return inputStream;
    }
  }
}
